// UdpClient.cc文件
#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Thread.hpp"

using namespace MyThread;

std::string server_ip;
uint16_t server_port;
int sockfd;
pthread_t recv_id;

void Send()
{
    // 填写服务器信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server)); // 先请0
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);                  // 主机转网络
    server.sin_addr.s_addr = inet_addr(server_ip.c_str()); // ip转4字节，4字节转网络序列
    // 发消息
    while (true)
    {
        std::string input;
        std::cout << "Please Enter# ";
        std::getline(std::cin, input); // 从输入流获取到input里
        sendto(sockfd, input.c_str(), input.size(), 0, (struct sockaddr *)&server, sizeof(server));

        if(input == "QUIT")
        {
            pthread_cancel(recv_id); // 把收消息的进程cancel
            break; // 然后自己退出
        }
    }
}


void Recv()
{
    while (true)
    {
        // 收消息
        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int m = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
        if (m > 0)
        {
            buffer[m] = 0;
            //std::cout << buffer << std::endl;
            std::cerr << buffer << std::endl;
        }
    }
}

// 格式为：udpclient server_ip server_port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage:" << argv[0] << " server_ip server_port" << std::endl;
        return 1;
    }
    server_ip = argv[1];
    server_port = std::stoi(argv[2]);

    // 1.创建套接字
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cout << "client创建套接字失败" << std::endl;
        return 2;
    }
    // 2.bind,但不需要显示的bind

    // 3.创建线程，主线程只要join就行
    Thread sender(Send);   // 此线程负责发消息
    Thread Receiver(Recv); // 此线程负责收消息
    sender.Start();
    Receiver.Start();

    recv_id = Receiver.Id(); // 获得收消息线程的id

    sender.Join();
    Receiver.Join();
    return 0;
}